// pages/my/information/information.js

import {
  CityList
} from '../../../components/wx-city-picker/pca.js';
//导入验证js
import WxValidate from "../../unity/WxValidate.js";
var util = require("../../unity/common.js");
const CryptoJS = require('crypto-js'); 

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    staticUrl: app.globalData.staticUrl,
    ischeck: false,
    iscommit: false,
    error: "",
    UserHouseholdlistIndex:'',
    UserAcademyListsIndex:'',
    isloadfromserver: false,
    sex: ["男", "女"],
    UserHouseholdlist:['深圳罗湖','深圳福田','深圳南山','深圳宝安','深圳龙岗',
    '深圳盐田','深圳龙华','深圳坪山','深圳光明','广东省非深圳','非广东'],
    UserCountryCode:"中国",
    UserCustodyRelationship:["父亲","母亲","爷爷","奶奶","外公","外婆","其他"],
    banduserlists:[],
    UserAcademyLists:[],
    ismodify:false,
    playerinfo: {
      userID: "",
      userOpenid: "",
      UserTrueName: "",
      UserBirthday: "",
      UserTypeCard: "身份证",
      UserMobile: "",
      UserEmail: "",
      UserCardNumber: "",
      UserCountry: "CHN",
      UserProvince: "",
      UserCity: "",
      UserRegion: "",
      UserAddress: "",
      UserAge:"",
      UserSchool: "",
      UserHousehold :"",
      UserMembershipNumber:"",
      UserSex: "",
      UserCustodyName: "",
      UserCustodyRelationship: "",
      UserCustodyMobile: "",
      
    },

    currentuserInfo:{},
    isnewband:false,
    ismodify:false, //可以修改生日和身份证,
    match_id:'',//比赛ID
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var ismodify = options.ismodify;

    this.setData({ismodify:ismodify});
    var match_id = options.match_id;
    if(match_id){
    this.setData({match_id:match_id});
  }
    console.log(this.data.ismodify);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.initValidate();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({currentuserInfo:app.globalData.userInfo});
    console.log(this.data.currentuserInfo);
    // this.getplayerInfo();
    this.getplayerInfo2();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


  changedata: function (e) {

    var playerinfo = this.data.playerinfo;
    var value = e.detail.value;
    var cat = e.target.id;
    console.log("changedata");
    console.log(e);
    if (cat == "UserSex") {
      playerinfo.UserSex = parseInt(value) * 1 +1;
    } else if (cat == "UserBirthday") {
      playerinfo.UserBirthday = value;
      this.checkbithday();
    } else if (cat == "UserTypeCard") {
      playerinfo.UserTypeCard = this.data.cardtype[value];
    } 
    else if (cat == "UserCountry") {
      playerinfo.UserCountry = this.data.national[value][0];
      var strnation =this.getnationl(playerinfo.UserCountry);
      this.setData({UserCountryCode:strnation});
      console.log(this.data.UserCountryCode);
      this.initValidate();//重新更新验证字段
      console.log(playerinfo);
    } else if (cat == "UserProvince" || cat == "UserCity" || cat == "UserRegion") {
      playerinfo.UserProvince = value[0];
      playerinfo.UserCity = value[1];
      playerinfo.UserRegion = value[2];
      console.log(value);
    }
   
 
    this.setData({
      playerinfo: playerinfo
    });
    console.log(this.data.playerinfo);
  },

  inputdata: function (e) {
    var playerinfo = this.data.playerinfo;
    var cat = e.target.id;
    var value = e.detail.value;
    console.log("inputdata");
    console.log(e);
    if (cat == "UserTrueName") {
      playerinfo.UserTrueName = value;
    }else if (cat == "UserAge") {
      playerinfo.UserAge = value;
    } else if (cat == "UserHousehold") {
      playerinfo.UserHousehold = value;
    } else if (cat == "UserAddress") {
      playerinfo.UserAddress = value;
    } else if (cat == "UserSchool") {
      playerinfo.UserSchool = value;
    } else if (cat == "UserMembershipNumber") {
      playerinfo.UserMembershipNumber = value;
    } else if (cat == "UserCustodyName") {
      playerinfo.UserCustodyName = value;
    }
    else if (cat == "UserEmail") {
      playerinfo.UserEmail = value;
    }
    else if (cat == "UserMobile") {
      playerinfo.UserMobile = value;
    }
    else if (cat == "UserCustodyMobile") {
      playerinfo.UserCustodyMobile = value;
    }
    else if (cat == "UserMembercard_MH") {
      playerinfo.UserMembercard_MH = value;
    }
    else if (cat == "UserIntroduce") {
      playerinfo.UserIntroduce = value;
    }
    else if(cat == "UserCardNumber"){
      console.log("UserCardNumber");
      console.log(playerinfo);
      playerinfo.UserCardNumber = value;
      if (playerinfo.UserTypeCard == '身份证' && util.checkIdCard(playerinfo.UserCardNumber)) {
       
        var bithyday = util.IdCard( playerinfo.UserCardNumber, 1);
        console.log("inputidcardno");
        console.log(bithyday);
        console.log(playerinfo.UserBirthday);
        if (playerinfo.UserBirthday && playerinfo.UserBirthday != bithyday) {
          this._errorshow("身份证中的出生年月日和您输入的不一致，请检查！");
          util.commontscrolltoview("UserCardNumber", this);
        }
  
      }
    
      
      
    }
   
    console.log(playerinfo);
    this.setData({
      playerinfo: playerinfo
    });
  },

  inputidcardno: function (e) {
   
   

  },

  checkbithday() {
    var playerinfo = this.data.playerinfo;
    var idcard = playerinfo.UserCardNumber;

    if (playerinfo.UserTypeCard == '身份证' && (idcard) && util.checkIdCard(idcard)) {
      var bithyday = util.IdCard(idcard, 1);
      console.log("checkbithday");
      console.log(bithyday);
      console.log(playerinfo.UserBirthday);

      if (playerinfo.UserBirthday == bithyday) {

      } else {
        this._errorshow("身份证中的出生年月日和您输入的不一致，请检查！");
        util.commontscrolltoview("UserBirthday", this);
      }
    }
  },

  filldata: function (userinfo) {
  console.log(userinfo);
    var playerinfo = { //增加playerinfo子元素
      UserTrueName: userinfo.UserTrueName,
      UserBirthday: userinfo.UserBirthday,
      UserTypeCard: (userinfo.UserTypeCard?userinfo.UserTypeCard:"身份证"),
      UserCardNumber: userinfo.UserCardNumber,
      comptioncategory: userinfo.comptioncategory,
      comptiongroup: userinfo.comptiongroup,
      UserAge: userinfo.UserAge,
      UserHousehold: userinfo.UserHousehold,
      UserCountry:userinfo.UserCountry,
      UserProvince: userinfo.UserProvince,
      UserCity: userinfo.UserCity,
      UserRegion: userinfo.UserRegion,
      UserAddress: userinfo.UserAddress,
      UserSchool: userinfo.UserSchool,
      UserHeight:userinfo.UserHeight,
      UserWeight:userinfo.UserWeight,
      UserMembershipNumber: userinfo.UserMembershipNumber,
      UserSex: userinfo.UserSex,
      UserCustodyName: userinfo.UserCustodyName==null?'':userinfo.UserCustodyName,
      UserCustodyRelationship:  userinfo.UserCustodyRelationship==null?'':userinfo.UserCustodyRelationship,
      UserCustodyMobile:  userinfo.UserCustodyMobile==null?'':userinfo.UserCustodyMobile,
      UserIntroduce:userinfo.UserIntroduce,
      UserMembercard_MH:userinfo.UserMembercard_MH,
      UserMobile: userinfo.UserMobile,
      UserEmail: userinfo.UserEmail,
      UserAcademyID:userinfo.UserAcademyID,

    }


    var strnation =this.getnationl(userinfo.UserCountry);
    //var UserAcademyindex = (userinfo.UserAcademyID)?this.getacademyindex(userinfo.UserAcademyID):'';
    //var UserHouseholdlistIndex =  (userinfo.UserHousehold)?this.getUserHouseholdindex(userinfo.UserHousehold):'';
    this.setData({
      UserCountryCode:strnation,
      playerinfo: playerinfo,
     // UserAcademyListsIndex:UserAcademyindex,
     // UserHouseholdlistIndex:UserHouseholdlistIndex,
    })

    console.log("this.data.playerinfo");
    console.log(this.data.playerinfo);
    this.initValidate();
  },
  filldata2: function (userinfo) {
    console.log(userinfo);
    console.log('---------------filldata2-------------------------');
    // 解密密钥
    const decryptKey = 'xjgolfq2025t0809'; 
    
    // 解码敏感信息
    let decryptedUserTrueName = userinfo.UserTrueName;
    let decryptedUserCardNumber = userinfo.UserCardNumber;
    let decryptedUserMobile = userinfo.UserMobile;
    
    try {
      // 解码真实姓名
      if (userinfo.UserTrueName) {
        decryptedUserTrueName = this.decryptData(userinfo.UserTrueName, decryptKey);
        console.log('解码后的真实姓名:', decryptedUserTrueName);
        
        // 只有当真实姓名存在且不为空时才设置标志
        if (decryptedUserTrueName && decryptedUserTrueName.trim() !== '') {
          var that = this;
          that.setData({
            isloadfromserver: true,
            ismodify: true,
          });
        }
      }
    } catch (error) {
      console.error('解码UserTrueName失败:', error);
      decryptedUserTrueName = userinfo.UserTrueName;
    }
    
    try {
      // 解码身份证号
      if (userinfo.UserCardNumber) {
        decryptedUserCardNumber = this.decryptData(userinfo.UserCardNumber, decryptKey);
        console.log('解码后的身份证号:', decryptedUserCardNumber);
      }
    } catch (error) {
      console.error('解码UserCardNumber失败:', error);
      decryptedUserCardNumber = userinfo.UserCardNumber; 
    }
    
    try {
      // 解码手机号
      if (userinfo.UserMobile) {
        decryptedUserMobile =   this.decryptData(userinfo.UserMobile, decryptKey);
        console.log('解码后的手机号:', decryptedUserMobile);
      }
    } catch (error) {
      console.error('解码UserMobile失败:', error);
      decryptedUserMobile = userinfo.UserMobile; 
    }
    
    var playerinfo = { //增加playerinfo子元素
      UserTrueName: decryptedUserTrueName, // 使用解码后的值
      UserBirthday: userinfo.UserBirthday,
      UserTypeCard: (userinfo.UserTypeCard?userinfo.UserTypeCard:"身份证"),
      UserCardNumber: decryptedUserCardNumber, // 使用解码后的值
      comptioncategory: userinfo.comptioncategory,
      comptiongroup: userinfo.comptiongroup,
      UserAge: userinfo.UserAge,
      UserHousehold: userinfo.UserHousehold,
      UserCountry:userinfo.UserCountry,
      UserProvince: userinfo.UserProvince,
      UserCity: userinfo.UserCity,
      UserRegion: userinfo.UserRegion,
      UserAddress: userinfo.UserAddress,
      UserSchool: userinfo.UserSchool,
      UserHeight:userinfo.UserHeight,
      UserWeight:userinfo.UserWeight,
      UserMembershipNumber: userinfo.UserMembershipNumber,
      UserSex: userinfo.UserSex,
      UserCustodyName: userinfo.UserCustodyName==null?'':userinfo.UserCustodyName,
      UserCustodyRelationship:  userinfo.UserCustodyRelationship==null?'':userinfo.UserCustodyRelationship,
      UserCustodyMobile:  userinfo.UserCustodyMobile==null?'':userinfo.UserCustodyMobile,
      UserIntroduce:userinfo.UserIntroduce,
      UserMembercard_MH:userinfo.UserMembercard_MH,
      UserMobile: decryptedUserMobile, // 使用解码后的值
      UserEmail: userinfo.UserEmail,
      UserAcademyID:userinfo.UserAcademyID,
    }

    var strnation =this.getnationl(userinfo.UserCountry);
    //var UserAcademyindex = (userinfo.UserAcademyID)?this.getacademyindex(userinfo.UserAcademyID):'';
    //var UserHouseholdlistIndex =  (userinfo.UserHousehold)?this.getUserHouseholdindex(userinfo.UserHousehold):'';
    this.setData({
      UserCountryCode:strnation,
      playerinfo: playerinfo,
     // UserAcademyListsIndex:UserAcademyindex,
     // UserHouseholdlistIndex:UserHouseholdlistIndex,
    })

    console.log("this.data.playerinfo");
    console.log(this.data.playerinfo);
    this.initValidate();
  },
  getUserHouseholdindex(id){
    var UserHouseholdlist = this.data.UserHouseholdlist;
    for(var index = 0 ;index < UserHouseholdlist.length;index++){
        if(UserHouseholdlist[index].id== id){
          return index;
        }
      }
  }
,

  getacademyindex(id){
    var UserAcademyLists = this.data.UserAcademyLists;
    for(var index = 0 ;index < UserAcademyLists.length;index++){
        if(UserAcademyLists[index].id== id){
          return index;
        }
    }
}
,
  getplayerInfo() {
    var that = this;
    wx.showLoading({
      title: '正在加载球员信息',
    })
    app.getbasicplayerinfo(function (res) {
        console.log("getplayerInfo");

        if (res.data.errorcode.code == "ok") {
          var UserAcademyLists = res.data.data.UserAcademyLists;
         // UserAcademyLists.unshift({id:0,name:"暂无"});
          that.setData({
            cardtype:res.data.data.cardtype,
           // UserCustodyWork:res.data.data.custodywork,
            national:res.data.data.national,
            UserAcademyLists:UserAcademyLists
          })
                  console.log('------------getplayerInfo--------------------')

          console.log(that.data.cardtype);
          console.log(that.data.UserAcademyLists);
          console.log(that.data.national);
          if (res.data.data &&res.data.data.user_info && res.data.data.user_info.UserTrueName) {
            that.filldata(res.data.data.user_info);
            that.setData({
              isloadfromserver: true,
              ismodify:true,
            });
          }
       
        }
      },
      function () {
        wx.hideLoading();
      }
    );
  },
 getplayerInfo2() {
    var that = this;
    wx.showLoading({
      title: '正在加载球员信息',
    })
    app.getbasicplayerinfo_encode(function (res) {
        console.log("getbasicplayerinfo_encode");

        if (res.data.errorcode.code == "ok") {
          var UserAcademyLists = res.data.data.UserAcademyLists;
         // UserAcademyLists.unshift({id:0,name:"暂无"});
          that.setData({
            cardtype:res.data.data.cardtype,
           // UserCustodyWork:res.data.data.custodywork,
            national:res.data.data.national,
            UserAcademyLists:UserAcademyLists
          })
         console.log('------------getplayerInfo2--------------------')
          console.log(that.data.cardtype);
          console.log(that.data.UserAcademyLists);
          console.log(that.data.national);
          if (res.data.data &&res.data.data.user_info && res.data.data.user_info.UserTrueName) {
            that.filldata2(res.data.data.user_info);
           
          }
       
        }
      },
      function () {
        wx.hideLoading();
      }
    );
  },

  onGetPhoneNumber (e){
    if(e.detail.code==null||e.detail.code==""){
      wx.showToast({
        title: '请允许获取您的手机号',
 
        'icon':'none',
 
      })
 
      return;
 
    }else{
       var that = this;
       var playerinfo = this.data.playerinfo;
      app.GetPhoneNumber(e.detail.code, function (res) {
        if(res.data.data){
          playerinfo.UserMobile = res.data.data;
          that.setData({playerinfo:playerinfo});
        }
  
      }, function () {
      
      })
    }
 
  },

  changebanduserlists:function (e) {

    var currentuserInfo = this.data.currentuserInfo;
    var banduserlists = currentuserInfo.banduserlists;
    var value = e.detail.value;
   
    console.log("changebanduserlistsfunction");
    console.log(e);

    app.globalData.userInfo.trueName = banduserlists[value].truename;
    app.globalData.userInfo.openid = banduserlists[value].openid ;
    app.globalData.userInfo.userID = banduserlists[value].userid ;
    app.globalData.userInfo.player_id = banduserlists[value].player_id ;
    app.globalData.userInfo.cardnumber = banduserlists[value].cardnumber ;
    console.log(app.globalData.userInfo);
    this.setData({currentuserInfo:app.globalData.userInfo, isnewband:false});
    // this.getplayerInfo();
     this.getplayerInfo2();
  },

  ///报名提交方法
  _registerformSubmit(e) {
    var playerinfo = this.data.playerinfo;
    console.log(playerinfo);
    if (!this.WxValidate.checkForm(playerinfo)) {
      //表单元素验证不通过，此处给出相应提示

      let error = this.WxValidate.errorList[0];
      console.log(error.param);


      switch (error.param) {
        case "UserTrueName":

          //TODO
          break;
          case "UserMobile":

          //TODO
       
        case "UserSex":
          //TODO
          break;
       
          case "UserMembershipNumber":
          //TODO
          break;
      
          case "UserCountry":
            //TODO
            break;
            case "UserBirthday":
            //TODO
            break;
            case "UserCardNumber":
            //TODO
            break;
            case "UserTypeCard":
            //TODO
            break;
       


      }
      console.log(util);
      // this.data.focuslist.removeChild();
      this._errorshow(error.msg);
      util.commontscrolltoview(error.param, this);

      return false;
    }
    
    
 
    console.log(playerinfo);


    playerinfo.userID = app.globalData.userInfo.userID;
    playerinfo.userOpenid = app.globalData.userInfo.openid;

    this.setData({
      ischeck: true,
      playerinfo: playerinfo
    });
    util.scrolltoview("dbcheck", this);
  },
 
  commit: function () {
    var that = this;
  
    that.setData({
      iscommit: true
    });
    wx.showLoading({
      title: '正在提交信息',
    })
   
    app.basicplayerinfo(this.data.playerinfo, function (res) {
      console.log("commit");
      console.log(res);
      if (res.data.errorcode.code = "ok") {
        var succuss =  {
          message: "球员信息提交成功，赛事开启报名时可以进行报名",
          time: new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString(),
          back: true,
          buttoninfo: "返回",
          match_id:that.data.match_id,
        };
         var message ="球员信息提交成功，赛事开启报名时可以进行报名";

        if(that.data.isloadfromserver){
          message = "球员信息修改成功";
        }
        else{
           //跳转到成功页面  关联用户playerID
           if(!that.data.isnewband){
            app.globalData.userInfo.player_id = res.data.data.playerid;
              app.globalData.userInfo.trueName = res.data.data.trueName;
              app.globalData.userInfo.cardnumber = res.data.data.cardnumber;
           }
           else{
              app.globalData.userInfo.player_id = res.data.data.playerid;
              app.globalData.userInfo.trueName = res.data.data.trueName;
              app.globalData.userInfo.cardnumber = res.data.data.cardnumber;
              app.globalData.userInfo.userID = res.data.data.userID;
              app.globalData.userInfo.banduserlists = res.data.data.banduserlists;
              console.log(app.globalData.userInfo);
           }
        }

        var isautologin =  wx.getStorageSync("isautologin");
        if(isautologin){
          wx.setStorageSync('userInfo', app.globalData.userInfo);
        }
        succuss.message  = message;
  
        wx.redirectTo({
          url: '/pages/succuss/index?succuss=' + JSON.stringify(succuss)

        })
      } else {
        wx.showToast({
          title: res.data.errorcode.message,
          duration:5000,
        })
      }

    }, function () {
      that.setData({
        iscommit: false,
        isnewband:false,
      });
      wx.hideLoading();
    })
  },

  back: function () {
    this.setData({
      ischeck: false
    });
  },


  _errorshow(msg) {
   this.setData({
      error: msg
    })
   var error = this.selectComponent('#toptips');
   error._error(this.data.error);
  },

   decryptData(encryptedData, key) {
    // encryptedData 是 base64 编码的 (IV + 密文)
    const encryptedDataBytes = CryptoJS.enc.Base64.parse(encryptedData);
    
    // AES 的块大小是 16 字节
    const ivSize = 16; // bytes
    const iv = CryptoJS.lib.WordArray.create(encryptedDataBytes.words.slice(0, ivSize / 4), ivSize);
    const ciphertext = CryptoJS.lib.WordArray.create(encryptedDataBytes.words.slice(ivSize / 4));
    
    // 解密
    const decrypted = CryptoJS.AES.decrypt(
        { ciphertext: ciphertext },
        CryptoJS.enc.Utf8.parse(key), // 将密钥字符串转为 WordArray
        {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        }
    );
    
    return decrypted.toString(CryptoJS.enc.Utf8);
} ,

  initValidate() {
  
   
      let rules  = {
      UserTrueName: {
        required: true,
        maxlength: 10
      },
      UserSex: {
        required: true
      },
     
      UserMobile: {
        required:true,
        tel:true,
      
      },
      UserBirthday: {
        required: true,

      },
      UserCountry: {
        required: true
      },
     
  
      UserCardNumber:{
          required: true,
          
      },
     
      UserTypeCard: {
        required:true,
      
      
      },
   
     
    

    }

    let message = {
      UserTrueName: {
        required: '请输入姓名',
        maxlength: '名字不能超过10个字'
      },
    
      UserMobile: {
        required: "请输入球员联系方式",
        tel: "请输入正确的球员联系方式"
      },
     
      UserSex: {
        required: "请选择您的性别",
      },
     
      UserBirthday: {
        required: '请输入生日',
        
      },
    
      UserCountry: {
        required: "请输入国籍/地区",
        
      },
    /* 
      UserMembershipNumber: {
        required: "请输入会员卡号",
      },
*/
      UserTypeCard: {
        required: "请输入证件类型",
      },

      UserCardNumber: {
        required: "请输入身份证件号",
      },

    }
    if(this.data.playerinfo.UserCountry == 'CHN'){
        rules.UserCardNumber={
          required: false,
          idcard: true
        };
        message.UserCardNumber={
          required: "请输入身份证件号码",
          idcard: "请输入正确的身份证件号码"
        };
    }
    else{
      rules.UserCardNumber={
        required: false,
       
      };
      message.UserCardNumber={
        required: "请输入身份证件号码",
       };
    }
    //实例化当前的验证规则和提示消息
    this.WxValidate = new WxValidate(rules, message);
  },

  getnationl(code){
      var national = this.data.national;
      console.log(national); 
      console.log(code);
      var strnation = "";
      for(var index=0;index<national.length; index++){
        console.log(national[index][0]); 
          if(national[index][0] == code){
            
            strnation =  national[index][1] ;
            break;
          }
      }
      console.log(strnation);
      return strnation;
  },

  bindnew:function(){
    var playerinfo = this.data.playerinfo;
    playerinfo.userID="";
    playerinfo.UserTrueName="";
    playerinfo.UserBirthday="";
    playerinfo.UserTypeCard="身份证";
    playerinfo.UserCardNumber="";
    playerinfo.UserCountry= "CHN";
    playerinfo.UserProvince="";
    playerinfo.UserCity="";
    playerinfo.UserRegion="";
    playerinfo.UserAddress="";
    playerinfo.UserAge="";
    playerinfo.UserSchool="";
    playerinfo.UserHousehold ="";
    playerinfo.UserMembershipNumber="";
    playerinfo.UserSex="";
    playerinfo.UserIntroduce="";
    playerinfo.UserMembercard_MH="";
    playerinfo.UserMobile="";
    playerinfo.UserEmail="";
    playerinfo.UserAcademyID="";

    playerinfo.isnewband = 1;
    console.log(playerinfo);
       this.setData({isnewband:true,
        isloadfromserver:false,
        UserAcademyListsIndex:'',
        UserHouseholdlistIndex:'',
        playerinfo:playerinfo});

  }

})